package com.lupan.jedis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.Set;

/**
 * Created by xiezhouyan on 16-3-3.
 */
@Component
public class RedisUtil {
    @Autowired(required = false)
    private RedisTemplate<String, String> redisTemplate;

    private RedisSerializer<String> keySerializer = new StringRedisSerializer();


    private byte[] rawKey(Object key) {
        Assert.notNull(key, "non null key required");
        if (key instanceof byte[]) {
            return (byte[]) key;
        } else if (key instanceof String) {
            return keySerializer.serialize((String) key);
        }
        return null;
    }

    public void delete(final Object key) {
        redisTemplate.execute(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                byte[] rawKey = rawKey(key);
                connection.del(rawKey);
                return null;
            }
        }, true);
    }

    public Set<byte[]> keys(final String key) {
        return (Set<byte[]>) redisTemplate.execute(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                byte[] rawKey = rawKey(key);
                connection.del(rawKey);
                return connection.keys(rawKey);
            }
        }, true);
    }

    public void delete(Set<byte[]> keys) {
        if (keys == null || keys.size() == 0) {
            return;
        }
        for (byte[] key : keys) {
            delete(key);
        }
    }
}
